package org.abc.manager 
{
	import flash.display.Stage;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import org.abc.interfaces.ITick;
	import org.abc.interfaces.ITickManager;
	/**
	 * 
	 * 单例模式类
	 * @describe 	timer tick
	 * @author 		Mr.zheng
	 * @time 		2011-7-28
	 */
	public class TimerTickManager implements ITickManager{
		private static var _instance:TimerTickManager = null;
		public function TimerTickManager(single:Single){
			
			if(single == null)
			{
				throw new Error("Can't create instance , Single is Null!");
			}
		}
		/**
		 * 单例引用
		 */
		public static function get instance():TimerTickManager
		{
			if(_instance == null)
			{
				_instance = new TimerTickManager(new Single());
			}
			return _instance;
		}
		
		//start-----------------------------------------------------------------------------
		private var _stage:Stage;
		/** _ticks[间隔时间]=Vector.<ITick> */
		private var _ticks:Dictionary;
		/** _timers[间隔时间]=Timer */
		private var _timers:Dictionary;
		/* INTERFACE blog.zihua2007.interfaces.ITickManager */
		
		public function init(gameStage:Stage):void 
		{
			_ticks = new Dictionary();
			_timers = new Dictionary();
			_stage = gameStage;
		}
		
		public function addTick(tick:ITick):void 
		{
			if (_ticks[tick.tickGap] == null) {
				_ticks[tick.tickGap] = new Vector.<ITick>();
				_timers[tick.tickGap] = new Timer(tick.tickGap);
				_ticks[tick.tickGap].push(tick);
				
				_timers[tick.tickGap].addEventListener(TimerEvent.TIMER, onTimer);
				_timers[tick.tickGap].start();
			}else {
				_ticks[tick.tickGap].push(tick);
				if(!Timer(_timers[tick.tickGap]).running){
					_timers[tick.tickGap].addEventListener(TimerEvent.TIMER, onTimer);
					_timers[tick.tickGap].start();
				}
			}
		}
		public function removeTick(tick:ITick):void 
		{
			if (_ticks[tick.tickGap] == null) return;
			var index:int = _ticks[tick.tickGap].indexOf(tick);
			if (index == -1) return;
			
			_ticks[tick.tickGap].splice(index, 1);
			if (_ticks[tick.tickGap].length <= 0) {
				_timers[tick.tickGap].stop();
				_timers[tick.tickGap].removeEventListener(TimerEvent.TIMER, onTimer);
			}
		}
		/* public function */
		
		/* private function */
		private function onTimer(e:TimerEvent):void 
		{
			var gap:int = (e.currentTarget as Timer).delay;
			for each (var item:ITick in _ticks[gap]) 
			{
				item.tick();
			}
			//e.updateAfterEvent();
		}
	}
}
class Single{}